import React from 'react';
import {FlatList, StyleSheet, Text, ScrollView} from 'react-native';
import {commonStyles} from '../../configs/commonStyle';
import BasePage from '../BasePage';
import {inject, observer} from 'mobx-react';
import {TouchableOpacity, View, Button} from 'react-native-ui-lib';
import {Card} from 'react-native-elements';
import _ from 'lodash';
import {logger} from '../../utils/util';
import navigator from "../../utils/navigator";

import {
  getWarehouseProductList,
  getOrderStatistics,
  outbound,
  finish,
  sally,
} from '../../net/transfer';
import ListEmpty from '../common/ListEmpty';
import Events from '../../utils/events';
import ToastUtils from '../../utils/ToastUtils';
import ConfirmDialog from '../common/ConfirmDialog';
import moment from 'moment';
import DateFilter from '../components/DateFilter';
import ExtractedCodeDialog from '../common/dialog/ExtractedCodeDialog';

const codeTypeMap = {
  'out': '提取码出库',
  'finish': '提取码送达',
}

/**
 * 中转蛋糕
 */
@inject('userStore', 'appStore')
@observer
export default class TransferCake extends BasePage {
  constructor(props) {
    super(props);
    this.outbounding = false; // 出库中
    this.finishing = false; // 送达中
    this.codeType = ''; // 提取码类型
    this.state = {
      timeStart: moment().format('YYYY-MM-DD'),
      timeEnd: moment().format('YYYY-MM-DD'),
      showOutedEmpty: true,
      showUnoutedEmpty: true,
      showStatisEmpty: true,
      outedList: [],
      unoutedList: [],
      statisList: [],
    };
  }

  componentDidMount() {
    this.loadData();
    this.transferScanOutEvent = Events.subscribe(
      'transferScanOut',
      this.handleScanOut,
    );
    this.transferScanFinishEvent = Events.subscribe(
      'transferScanFinish',
      this.handleScanFinish,
    );
  }

  componentWillUnmount() {
    this.transferScanOutEvent && this.transferScanOutEvent.remove();
    this.transferScanFinishEvent && this.transferScanOutEvent.remove();
  }

  // 扫码出库
  handleScanOut = result => {
    if (this.outbounding) {
      return;
    }
    try {
      const parseRes = JSON.parse(result)
      const orderDetailId = (parseRes && parseRes.orderDetailId) || parseRes
      if (orderDetailId) {
        this.outbounding = true;
        this.handleOutbound(orderDetailId).finally(() => {
          this.outbounding = false;
        });
      } else {
        ToastUtils.showFailInfo('识别订单号失败，请重试');
      }
    } catch (error) {
      logger('识别订单号失败，请重试')
      ToastUtils.showFailInfo('识别订单号失败，请重试');
    }
  };

  handleOutbound = (orderDetailId) => {
    const { location } = this.props.userStore;
    return outbound({
      orderDetailId: orderDetailId,
      longitude: location.longitude,
      latitude: location.latitude,
    })
      .then(res => {
        ToastUtils.showSuccessInfo(res.msg || '出库成功');
        return res
      })
      .catch(err => {
        ToastUtils.showFailInfo(err?.msg || '出库失败，请重试');
        return err
      })
  }

  // 扫码送达
  handleScanFinish = result => {
    if (this.finishing) {
      return;
    }
    try {
      const parseRes = JSON.parse(result)
      const orderDetailId = (parseRes && parseRes.orderDetailId) || parseRes
      if (orderDetailId) {
      this.finishing = true;
      this.handleFinish(orderDetailId).finally(() => {
        this.finishing = false;
      });
      } else {
        ToastUtils.showFailInfo('识别订单号失败，请重试');
      }
    } catch (error) {
      ToastUtils.showFailInfo('识别订单号失败，请重试');
    }
  };

  handleFinish = (orderDetailId) => {
    const { location } = this.props.userStore;
    return finish({
      orderDetailId: orderDetailId,
      longitude: location.longitude,
      latitude: location.latitude,
    })
      .then(res => {
        logger('handleFinish-then', res)
        ToastUtils.showSuccessInfo('送达成功');
        return res
      })
      .catch(err => {
        logger('handleFinish-catch', err)
        ToastUtils.showFailInfo(err?.msg || '送达失败，请重试');
        return err
      })
  }

  // 出发确认
  sally = () => {
    this.confirmDialog.show('请确认是否出发?');
  };
  // 触发出发
  handleSally = () => {
    sally()
      .then(res => {
        ToastUtils.showSuccessInfo('出发成功');
        this.loadData();
      })
      .catch(err => {
        ToastUtils.showFailInfo(err?.msg || '出发失败，请重试');
      });
  };

  // 开启扫码页面
  openScanPage = eventName => {
    this.setState({scanning: true});
    this.jumpToPage('ScanQrcodePage', {
      eventName,
      backCallback: () => this.loadData(),
    });
  };

  // 打开提取码页面
  openCodeDialogPage = codeType => {
    this.codeType = codeType
    this.extractedCodeDialog.show(codeTypeMap[codeType])
  };

  // 提取码处理
  handleCodeConfirm = (result) => {
    const { orderDetailId } = result
    if (!orderDetailId) {
      ToastUtils.showFailInfo('提取码解析失败，请重试');
      return
    }
    if (this.codeType === 'out') {
      this.handleOutbound(orderDetailId).then((res) => {
        if (res.code == 200) {
          this.loadData();
        }
      })
    } else if (this.codeType === 'finish') {
      this.handleFinish(orderDetailId).then((res) => {
        if (res.code == 200) {
          this.loadData();
        }
      })
    }
  }

  // 获取数据
  loadData = () => {
    this.getWarehouseProductList(1);
    this.getWarehouseProductList(2);
    this.getOrderStatistics();
  };

  // 获取1已出库/2未出库蛋糕列表
  getWarehouseProductList = (type) => {
    const {timeStart, timeEnd} = this.state;
    return getWarehouseProductList({
      timeStart: `${timeStart} 00:00:00`,
      timeEnd: `${timeEnd} 23:59:59`,
      type,
      showLoading: true,
    }).then(res => {
      this.setWarehouseData({type, result: res.result || []})
    });
  };

  // 蛋糕列表
  setWarehouseData = ({type, result = []}) => {
    const dataList = Object.keys(result).map(key => {
      return {
        name: key,
        text: result[key].length || 0,
        list: result[key],
        type,
      };
    })
    if (type == 1) {
      this.setState({
        outedList: dataList,
        showOutedEmpty: IsNullOrEmpty(result),
      })
    } else if (type == 2) {
      this.setState({
        unoutedList: dataList,
        showUnoutedEmpty: IsNullOrEmpty(result),
      })
    }
  }

  // 获取统计数据
  getOrderStatistics = () => {
    const {timeStart, timeEnd} = this.state;
    return getOrderStatistics({
      timeStart: `${timeStart} 00:00:00`,
      timeEnd: `${timeEnd} 23:59:59`,
    }).then(res => {
      logger(res);
      if (!IsNullOrEmpty(res?.result)) {
        this.setState({
          statisList: Object.keys(res.result).map(key => {
            const val = res.result[key];
            return {
              name: key,
              text: `${val['3']} / ${val['2']} / ${val['1']}`,
            };
          }),
          showStatisEmpty: IsNullOrEmpty(res.result),
        });
      } else {
        this.setState({
          statisList: [],
          showStatisEmpty: true,
        });
      }
    });
  };

  renderItem({item, index}) {
    return (
      <TouchableOpacity
        activeOpacity={1}
        onPress={() => {
          navigator.navigate('TransferCakeList', {item})
        }}
        style={styles.menu}>
        <View style={{...styles.menu_container, backgroundColor: item.bgColor}}>
          <Text style={commonStyles.text_black_20_bold}>{item.text}</Text>
          <Text style={{...commonStyles.text_gray_13, marginTop: 5}}>
            {item.name}
          </Text>
        </View>
      </TouchableOpacity>
    );
  }

  renderStaticItem({item, index}) {
    return (
      <View style={styles.menu}>
        <View style={{...styles.menu_container, backgroundColor: item.bgColor}}>
          <Text style={commonStyles.text_black_20_bold}>{item.text}</Text>
          <Text style={{...commonStyles.text_gray_13, marginTop: 5}}>
            {item.name}
          </Text>
        </View>
      </View>
    );
  }

  render() {
    const {outedList, unoutedList, statisList} = this.state;
    return (
      <View style={{flex: 1}}>
        <View
          row
          centerV
          style={{
            backgroundColor: '#fff',
            borderColor: '#eee',
            borderBottomWidth: 1,
          }}>
          <DateFilter
            onQueryClick={(timeStart, timeEnd) =>
              this.setState(
                {
                  timeStart,
                  timeEnd,
                },
                () => this.loadData(),
              )
            }
          />
          <TouchableOpacity
            activeOpacity={1}
            throttleTime={1000}
            style={styles.btn}
            onPress={this.loadData}>
            <Text style={commonStyles.text_black}>刷新</Text>
          </TouchableOpacity>
        </View>
        <View style={styles.btn_container}>
          <Button
            label="出库"
            style={styles.btn_item}
            size="small"
            color="#333"
            onPress={() => this.openScanPage('transferScanOut')}></Button>
          <Button
            label="出发"
            style={styles.btn_item}
            size="small"
            color="#333"
            onPress={this.sally}></Button>
          <Button
            label="送达"
            style={styles.btn_item}
            size="small"
            color="#333"
            onPress={() => this.openScanPage('transferScanFinish')}></Button>
          <Button
            label="提取码出库"
            style={styles.btn_item}
            size="small"
            color="#333"
            onPress={() => this.openCodeDialogPage('out')}></Button>
          <Button
            label="提取码送达"
            style={styles.btn_item}
            size="small"
            color="#333"
            onPress={() => this.openCodeDialogPage('finish')}></Button>
        </View>
        <ScrollView style={{flex: 1}}>
          <View>
            <Card title="未入库蛋糕">
              <FlatList
                data={unoutedList}
                renderItem={this.renderItem}
                keyExtractor={item => item.id}
                numColumns={3}
                ListEmptyComponent={() => (
                  <ListEmpty showEmpty={this.state.showUnoutedEmpty} desc="暂无数据" />
                )}
              />
            </Card>
            <Card title="已入库蛋糕">
              <FlatList
                data={outedList}
                renderItem={this.renderItem}
                keyExtractor={item => item.id}
                numColumns={3}
                ListEmptyComponent={() => (
                  <ListEmpty showEmpty={this.state.showOutedEmpty} desc="暂无数据" />
                )}
              />
            </Card>
            <Card title="送达 / 中转中 / 出库">
              <FlatList
                data={statisList}
                renderItem={this.renderStaticItem}
                keyExtractor={item => item.id}
                numColumns={3}
                ListEmptyComponent={() => (
                  <ListEmpty
                  showEmpty={this.state.showStatisEmpty}
                    desc="暂无数据"
                  />
                )}
              />
            </Card>
          </View>
        </ScrollView>

        <ConfirmDialog
          ref={r => (this.confirmDialog = r)}
          callBack={() => this.handleSally()}
        />
        <ExtractedCodeDialog 
          ref={r => (this.extractedCodeDialog = r)}
          callBack={this.handleCodeConfirm}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  menu: {
    ...commonStyles.center,
    width: '33.3%',
    backgroundColor: 'white',
    marginRight: 1,
  },
  menu_container: {
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: 5,
    width: 98,
    height: 70,
  },
  btn: {
    width: 80,
    height: 40,
    ...commonStyles.center,
    backgroundColor: '#F9D63B',
    borderRadius: 5,
    marginBottom: 5,
  },
  btn_container: {
    paddingTop: 10,
    paddingBottom: 10,
    backgroundColor: '#fff',
    flexDirection: 'row',
    flexWrap: 'wrap',
    borderColor: '#eee',
    borderBottomWidth: 1,
  },
  btn_item: {
    marginLeft: 10,
    marginBottom: 5
  }
});
